module repository.PlaylinkRepo;

import d2sqlite3;

import model.TeleplayVlink;
import model.MovieVlink;
import model.AnimationVlink;
import utils.ConstValue;

class PlaylinkRepo
{
    Database db;
    this ()
    {
        db = Database(Const.connStr);
    }

    ~this ()
    {
        db.close();
    }

    /** 
     * 查询真实部分地址
     * Params:
     *   vtable = 表名
     *   url = 原url地址
     * Returns: real_url
     */
    string getRealUrl (string vtable, string url)
    {
        Statement statement;
        switch (vtable)
        {
        case "teleplay_vlinks":
            statement = db.prepare(
                "SELECT real_url FROM teleplay_vlinks WHERE url=:url and real_url not null LIMIT 1;");
            break;
        case "movie_vlinks":
            statement = db.prepare(
                "SELECT real_url FROM movie_vlinks WHERE url=:url and real_url not null LIMIT 1;");
            break;
        case "animation_vlinks":
            statement = db.prepare(
                "SELECT real_url FROM animation_vlinks WHERE url=:url and real_url not null LIMIT 1;");
            break;
        default:
            return "";
        }
        statement.bind(":url", url);
        ResultRange result = statement.execute();
        scope (exit)
        {
            statement.reset();
        }
        if (result.empty)
        {
            return "";
        }
        auto row = result.front;
        string realUrl = row["real_url"].as!string;
        return realUrl;
    }

    /** 
     * 更新信息
     * Params:
     *   vtable = 表名
     *   url = 原url地址
     *   realUrl = 真实播放地址
     * Returns: bool
     */
    bool updateLinkInfo (string vtable, string url, string realUrl)
    {
        Statement statement;
        switch (vtable)
        {
        case "teleplay_vlinks":
            statement = db.prepare(
                "UPDATE teleplay_vlinks SET real_url=:real_url WHERE url=:url;");
            break;
        case "movie_vlinks":
            statement = db.prepare(
                "UPDATE movie_vlinks SET real_url=:real_url WHERE url=:url;");
            break;
        case "animation_vlinks":
            statement = db.prepare(
                "UPDATE animation_vlinks SET real_url=:real_url WHERE url=:url;");
            break;
        default:
            return false;
        }
        statement.bind(":real_url", realUrl);
        statement.bind(":url", url);
        statement.execute();
        return db.changes > 0;
    }
}
